package cn.calm.xhtml.contentassist.autocomplete;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;

import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import cn.calm.xhtml.XhtmlActivator;
import cn.calm.xhtml.entity.Attr;
import cn.calm.xhtml.entity.Tag;

@SuppressWarnings("restriction")
public class TagCache {

	public static List<ElementProcessorCompletionProposal> getElementProcessors(
			IJavaProject currentJavaProject,
			ArrayList<QName> findNodeNamespaces, String pattern) {
		Map<IProject, Map<String, Set<Tag>>> namespaces = XhtmlActivator
				.getNamespaces();
		Map<String, Set<Tag>> map = namespaces.get(currentJavaProject
				.getProject());
		List<ElementProcessorCompletionProposal> result = new ArrayList<>();
		if (map == null) {
			return result;
		}
		for (QName name : findNodeNamespaces) {
			Set<Tag> set = map.get(name.getNamespaceURI());
			if (set == null) {
				continue;
			}
			for (Tag t : set) {
				if ((name.getPrefix() + ":" + t.getName()).startsWith(pattern)) {
					result.add(new ElementProcessorCompletionProposal(t, name,
							pattern));
				}
			}
		}
		return result;
	}

	public static List<AttrProcessorCompletionProposal> getAttrProcessors(
			IJavaProject currentJavaProject, IDOMNode node, String pattern) {
		String namespaceURI = node.getNamespaceURI();
		Map<IProject, Map<String, Set<Tag>>> namespaces = XhtmlActivator
				.getNamespaces();
		Map<String, Set<Tag>> map = namespaces.get(currentJavaProject
				.getProject());
		List<AttrProcessorCompletionProposal> result = new ArrayList<>();
		if (map == null) {
			return result;
		}
		Set<Tag> set = map.get(namespaceURI);
		if (set == null) {
			return result;
		}
		Tag temp = null;
		String localName = node.getLocalName();
		for (Tag t : set) {
			String name = t.getName();
			if (localName.equals(name)) {
				temp = t;
				break;
			}
		}
		if (temp == null) {
			return result;
		}
		Set<Attr> attrs = temp.getAttrs();
		NamedNodeMap attributes = node.getAttributes();
		int length = attributes.getLength();
		List<String> existNames = new ArrayList<>(length);
		for (int i = 0; i < length; i++) {
			Node item = attributes.item(i);
			// String localName2 = item.getLocalName();
			existNames.add(item.getLocalName());
			// System.out.println(localName2);
		}
		for (Attr a : attrs) {
			String name = a.getName();
			if (!existNames.contains(name)) {
				if (name.startsWith(pattern)) {
					result.add(new AttrProcessorCompletionProposal(a, pattern));
				}
			}

		}
		return result;
	}

}
